package com.cl.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cl.common.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@RestController
public class GetRController {
    @Value("${server-url.nacos-hello-service}")
    private String HELLO_SERVICE_URL;

    private final RestTemplate restTemplate;

    public GetRController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/consumer/{id}")
    @SentinelResource(value = "fallBack",fallback = "fb",blockHandler = "bh")
    public AjaxResult getHello(@PathVariable String id) {
        String template = restTemplate.getForObject(HELLO_SERVICE_URL + "/nacos/" + id, String.class);
        if (Objects.equals(id, "4")){
            throw new IllegalArgumentException("非法参数");
        }else if (Objects.equals(id, "5")){
            throw new NullPointerException("记录不存在");
        }
        AjaxResult success = AjaxResult.success();
        success.put("success",template);
        return success;
    }

    public AjaxResult fb(@PathVariable String id,Throwable e) {
        AjaxResult ajaxResult = AjaxResult.error();
        ajaxResult.put("fbe", e.getMessage());
        return ajaxResult;
    }
    public AjaxResult bh(@PathVariable String id,BlockException e) {
        AjaxResult ajaxResult = AjaxResult.error();
        ajaxResult.put("bhe", e.getMessage());
        return ajaxResult;
    }
}
